package com.tender.impl;

import com.alibaba.fastjson.JSON;
import com.tender.RouterDiscoveryBizService;
import com.tender.SummaryBizService;
import com.tender.dto.HostInfoDTO;
import com.tender.enums.ServiceTypeEnums;
import com.tender.integration.acl.WebSocketServerApiACL;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SummaryBizServiceImpl implements SummaryBizService  {

    @Autowired
    private RouterDiscoveryBizService routerDiscoveryBizService;

    @Autowired
    private WebSocketServerApiACL webSocketServerApiACL;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public Integer summaryAll() {
        long start = System.currentTimeMillis();
        log.info("【汇总所有登录用户】start: {} -------- start ----------", start);
        List<HostInfoDTO > hostInfoDTOList = routerDiscoveryBizService.getHostInfoList(ServiceTypeEnums.WS.name(), null);
        if (!CollectionUtils.isEmpty(hostInfoDTOList)) {
            CountDownLatch countDownLatch = new CountDownLatch(hostInfoDTOList.size());
            List<Integer> list = new ArrayList<>();
            // 并发跑任务，提高响应速度
            hostInfoDTOList.forEach(hostInfoDTO -> {
                try {
                    threadPoolTaskExecutor.execute(() -> {
                        try {
                            log.info("【汇总所有登录用户】hostInfo: {} -------- start ----------", JSON.toJSONString(hostInfoDTO));
                            list.add(webSocketServerApiACL.userCount(hostInfoDTO.getApplicationName()));
                            log.info("【汇总所有登录用户】hostInfo: {} -------- end ----------", JSON.toJSONString(hostInfoDTO));
                            countDownLatch.countDown();
                        } catch (Exception e) {
                            log.error("【汇总所有登录用户】hostInfo: {},任务处理异常:", JSON.toJSONString(hostInfoDTO), e);
                        }
                    });
                } catch (Exception e) {
                    log.error("【汇总所有登录用户】hostInfo: {}, 提交任务失败:", JSON.toJSONString(hostInfoDTO), e);
                    countDownLatch.countDown();
                }
            });

            try {
                countDownLatch.await(2 * 60, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                // do nothing!
            }

            return list.stream().reduce(0, Integer::sum);
        }

        log.info("【汇总所有登录用户】end: {} -- seconds -------- end ----------", (System.currentTimeMillis() -start) / 1000);
        return 0;
    }
}
